package com.mrd.modules.quartz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.mrd.config.SpringUtil;
import com.mrd.modules.quartz.impl.SysJobEntity;
import com.mrd.modules.quartz.impl.SysJobService;

/**
 * 初始化调度器，先手动初始化，添加要执行的定时器，后面改造成读取数据库
 * 
 * @author han
 */
@Component
public class TaskInitBean {

  @Autowired
  SchedulerFactoryBean schedulerFactoryBean;
  @Autowired
  private SysJobService sysJobService;
  @Autowired
  private SpringUtil springUtil;

  /**
   * spring 初始化方法，把要调度的定时器在这里初始化
   * 
   * @auhtor han
   */
  public void init() throws Exception {
    List<SysJobEntity> list = sysJobService.queryList(new HashMap());
    if (list != null && list.size() > 0) {
      Scheduler scheduler = schedulerFactoryBean.getScheduler();
      List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
      List<Trigger> triggers = new ArrayList<Trigger>();
      for (SysJobEntity sysJob : list) {
        if (StringUtils.isNotEmpty(sysJob.getJobStatus()) && sysJob.getJobStatus().equals("1")) {
          addJob(sysJob);
        }
      }
    }
  }

  /**
   * 添加任务
   * 
   * @author han
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void addJob(SysJobEntity job) throws Exception {
    if (job == null || !SysJobEntity.STATUS_RUNNING.equals(job.getJobStatus())) {
      return;
    }

    Scheduler scheduler = schedulerFactoryBean.getScheduler();
    TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
    // Class clazz = (Class.forName(job.getBeanClass()).newInstance()).getClass();
    MethodInvokingJobDetailFactoryBean methodInvokingJob = new MethodInvokingJobDetailFactoryBean();
    methodInvokingJob.setTargetObject(springUtil.getBean(job.getJobName()));
    methodInvokingJob.setTargetMethod(job.getBeanClass());
    methodInvokingJob.setTargetBeanName(job.getJobName());
    methodInvokingJob.setName(job.getJobName());
    methodInvokingJob.setGroup(job.getJobGroup());
    methodInvokingJob.afterPropertiesSet();// 将管理Job类提交到计划管理类
    JobDetail jobDetail = methodInvokingJob.getObject();
    jobDetail.getJobDataMap().put("scheduleJob", job);
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
    trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
        .withSchedule(scheduleBuilder).build();
    scheduler.scheduleJob(jobDetail, trigger);

  }

}
